package com.hsw.habit.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hsw.habit.frame.utils.MD5Util;
import com.hsw.habit.frame.utils.TextUtils;
import com.hsw.habit.frame.utils.TokenUtils;
import com.hsw.habit.mapper.UserMapper;
import com.hsw.habit.model.JsonData;
import com.hsw.habit.model.User;
import com.hsw.habit.service.UserService;
import com.mysql.cj.util.Base64Decoder;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import javax.annotation.Resource;
import java.io.Serializable;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public User findUserById(int id) {
        return userMapper.selectUserById(id);
    }

    @Override
    public void insert(User user) {
        userMapper.insert(user);
    }

    @Override
    public User findUserByPhone(String phone) {
        return userMapper.selectUserByPhone(phone);
    }

    @Override
    public JsonData login(String phone, String password) {
        try {
            User formatUser = findUserByPhone(phone);
            if (null == formatUser) {
                return JsonData.error(4003,"该手机号未注册");
            }

            if (!MD5Util.md5(password).equals(formatUser.getPassword())) {
                return JsonData.error(4001,"密码错误");
            }
            formatUser.setPassword("");
            formatUser.setToken(TokenUtils.createJwtToken(phone));
            return JsonData.success(formatUser);
        } catch (Exception e) {
            return JsonData.error(4001, "登录失败");
        }
    }

    @Override
    public boolean update(User user) {
        return userMapper.updateByPrimaryKeySelective(user) == 1;
    }

    @Override
    public JsonData register(User user) {
        try {
            String phone = user.getPhone();
            String password = user.getPassword();
            User formatUser = findUserByPhone(phone);
            if (null != formatUser) {
                return JsonData.error(4002, "该手机号已注册");
            }
            if (TextUtils.isEmpty(user.getUserName())) {
                user.setUserName(user.getPhone());
            }
            user.setPassword(MD5Util.md5(password));
            insert(user);
        } catch (Exception e) {
            return JsonData.error(4001, e.getMessage());
        }


        return JsonData.success();
    }
}
